<template>
  <div class="common-layout">
    <Navbarheader />
    <div class="page-container">
      <el-container>
        <el-aside class="sidebar">
          <el-menu
            v-if="menuList.length > 0"
            :default-active="activeId"
            active-text-color="#409eff"
            @select="handleSelect"
          >
            <el-menu-item v-for="item in menuList" :key="item.id" :index="item.id">
              {{ item.title }}
            </el-menu-item>
          </el-menu>
          <el-empty v-else description="暂无项目" />
        </el-aside>

        <el-main class="main-content">
          <el-card v-loading="loading" shadow="never">
            <template v-if="detail">
              <div class="markdown-body article-content" v-html="renderedHtml"></div>
              <el-text type="info" size="small">
                {{ detail.createdAt }}
              </el-text>
            </template>
            <template v-else>
              <el-empty description="请选择左侧条目" />
            </template>
          </el-card>
        </el-main>
      </el-container>
    </div>
  </div>
</template>

<script setup lang="ts">
import Navbarheader from '@/components/userNavbar-header.vue'
import { ref, onMounted } from 'vue'
import MarkdownIt from 'markdown-it'
import hljs from 'highlight.js'
import 'github-markdown-css/github-markdown.css'
import { http } from '@/http'

// ... (您现有的 <script> 内容保持不变)

const highlight = (str: string, lang: string): string => {
  if (lang && hljs.getLanguage(lang)) {
    try {
      return `<pre class="hljs"><code>${hljs.highlight(str, { language: lang, ignoreIllegals: true }).value}</code></pre>`
    } catch (__) {
      return `<pre class="hljs"><code>${md.utils.escapeHtml(str)}</code></pre>`
    }
  }
  return `<pre class="hljs"><code>${md.utils.escapeHtml(str)}</code></pre>`
}

const md: MarkdownIt = new MarkdownIt({
  highlight: highlight,
})

interface MenuItem {
  id: string
  title: string
}

interface Detail {
  id: string
  title: string
  summary: string
  contentMd: string
  createdAt: Date
  updatedAt: Date
}

const menuList = ref<MenuItem[] | any>([])
const activeId = ref<string | null>(null)
const detail = ref<Detail | null>(null)
const loading = ref(false)
const renderedHtml = ref('')

const fetchMenu = async () => {
  try {
    const res: any = await http.get<MenuItem[]>('/api/articles/list')
    menuList.value = res

    if (menuList.value.length > 0) {
      const firstId = menuList.value[0].id.toString() // 确保ID是字符串
      activeId.value = firstId
      fetchDetail(firstId)
    }
  } catch (error) {
    console.error(error)
  }
}

const fetchDetail = async (id: string) => {
  loading.value = true
  try {
    const res: any = await http.get<string>(`/api/articles/${id}/content`)
    const markdown = res
    const articleInfo = menuList.value.find((item: any) => item.id.toString() === id)
    renderedHtml.value = md.render(markdown)
    detail.value = {
      id,
      title: articleInfo?.title || '',
      summary: '',
      contentMd: markdown,
      createdAt: new Date(),
      updatedAt: new Date(),
    }
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}

const handleSelect = (id: string) => {
  activeId.value = id
  fetchDetail(id)
}

onMounted(() => {
  fetchMenu()
})
</script>

<style scoped>
/* --- 默认样式 (桌面端) --- */
.page-container {
  padding: 2rem 1rem;
}

.el-container {
  max-width: 1200px;
  margin: 0 auto;
}

.sidebar {
  width: 240px;
  margin-right: 20px;
  flex-shrink: 0; /* 防止侧边栏被压缩 */
}

/* === 核心修改：美化 el-menu === */
.sidebar .el-menu {
  border-right: none; /* 移除自带的右边框 */
  background-color: transparent; /* 让菜单背景透明，与父容器融合 */
}

/* 菜单项的样式 */
.sidebar .el-menu-item {
  margin-bottom: 8px; /* 增加菜单项之间的间距 */
  border-radius: 6px; /* 增加圆角 */
  height: 48px; /* 增加高度，使其更易点击 */
  font-size: 15px; /* 调整字体大小 */
}

/* 鼠标悬停在菜单项上时的样式 */
.sidebar .el-menu-item:hover {
  background-color: #ecf5ff; /* 淡蓝色背景 */
  color: #409eff;
}

/* 当前激活（选中）的菜单项的样式 */
.sidebar .el-menu-item.is-active {
  background-color: #b6d1ec; /* 主题色背景 */
  color: #fff; /* 白色文字 */
  font-weight: bold;
}
/* === 美化结束 === */

.main-content {
  padding: 0;
}

.article-content {
  padding: 0 1em;
  max-width: 100%;
}

.markdown-body {
  font-family:
    -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif,
    'Apple Color Emoji', 'Segoe UI Emoji';
  font-size: 16px;
  line-height: 1.6;
  color: #24292e;
}

.hljs {
  background: #f6f8fa;
  padding: 1em;
  border-radius: 6px;
  overflow-x: auto;
  font-size: 14px;
}

/* --- 移动端适配 --- */
@media (max-width: 768px) {
  .page-container {
    padding: 1rem 0.5rem;
  }

  .el-container {
    flex-direction: column;
  }

  .sidebar {
    width: 100%;
    margin-right: 0;
    margin-bottom: 20px;
  }

  .main-content {
    width: 100%;
  }

  /* 移动端菜单项可以适当减小高度 */
  .sidebar .el-menu-item {
    height: 44px;
  }
}
</style>
